/**
 *Author: guanpf 992093924@qq.om
 *Date: 2023-06-26 16:03:37
 *LastEditTime: 2023-10-07 17:36:58
 *LastEditors: guanpf
 *Description: 
 *FilePath: /ZCGL_WX/src/api/base.js
 */
import axios from 'axios'
import Vue from 'vue'
import store from "@/store";
import  { ToastPlugin } from 'vux'

import router from '@/router'
Vue.use(ToastPlugin)

let vm = new Vue()

// import { toast  } from 'vux'

// console.log(4,this.$vux.toast)

// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
  headers: {
    'Cache-Control': 'no-cache',
  }
})

service.defaults.headers.post["Content-Type"] = "application/json";
// request interceptor
service.interceptors.request.use(config => {
    let token = store.state.user.userInfo.token
    if(token){
        config.headers["Authorization"] = `Bearer ${token}`;
    }else{
        config.headers["Authorization"] = "Basic aW90YmQtZHZlOmlvdGJkLWR2ZQ==";
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async response => {
    const res = response.data
    
    // if the custom code is not 20000, it is judged as an error.
    if(res.code === "0000"){
      return res
    }else if(res.errCode == "-99" && res.code === "0001"){
      // 未登录跳转登录页面
      router.push({name:"login"})
    }else{
      vm.$vux.toast.show ({
        text: res.message || 'Error',
        type: 'warn',
        time: 5 * 1000
      })
    
      Promise.reject(new Error(res.message || 'Error')).catch((e) => {})
      return res
    } 
  },
  error => {
    console.log('err' + error) // for debug
    vm.$vux.toast.show ({
      text: error.message,
      type: 'warn',
      time: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
